import React, { Component } from 'react';
import './verifyCode.scss';

interface VerifyCodeState {
    sent: boolean;
    countDown?: number;
}
interface VerifyCodeProps {
    sendInterval?: number;
    label?: string;
    className?: string;
}
export default class VerifyCode extends Component<VerifyCodeProps, VerifyCodeState> {
    static defaultProps: VerifyCodeProps = {
        label: '获取验证码',
        className: '',
        sendInterval: 60
    };
    timer: number;
    state: VerifyCodeState = {
        sent: false,
        countDown: this.props.sendInterval
    };

    sendVerifyCode = () => {
        const { sent } = this.state;
        const { sendInterval } = this.props;

        if (!!sent) {
            return;
        }
        this.setState({
            sent: true
        });
        this.timer = window.setInterval(
            () => {
                const { countDown } = this.state;
                if (countDown === 0) {
                    this.setState({
                        countDown: sendInterval,
                        sent: false
                    });
                    window.clearInterval(this.timer);
                } else {
                    this.setState({
                        countDown: countDown! - 1
                    });
                }
            },
            1000
        );
    }
    render(): JSX.Element {
        const { label, className } = this.props;
        const { sent, countDown } = this.state;
        return (
            <section 
                onClick={this.sendVerifyCode} 
                className={`${className ? ' ' + className : ''}`}
            >
                {sent ? countDown + 's' : label}
            </section>
        );
    }
}